import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

import { Modal, Button } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import menuList from '../../config/menuConfig'
import { reqWeather } from '../../api'
import { formatDate } from '../../utils/dateUtils'
import memory from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import './index.less'

const { confirm } = Modal
// 头部组件
class Header extends Component {
  state = {
    currentTime: formatDate(Date.now()),
    dayPictureUrl: 'http://api.map.baidu.com/images/weather/day/qing.png',
    weather: '晴'
  }
  getTime = () => {
    this.intervalID = setInterval(() => {
      const currentTime = formatDate(Date.now())
      this.setState({currentTime})
    }, 1000)
  }
  getWeather = async() => {
    const {dayPictureUrl, weather} = await reqWeather('北京')
    this.setState({dayPictureUrl, weather})
  }
  getTitle = () => {
    const path = this.props.location.pathname
    let title
    menuList.forEach(item => {
      if(item.key === path) {
        title = item.title
      } else if(item.children) {
        const cItem = item.children.find(cItem => path.indexOf(cItem.key) === 0)
        if(cItem) {
          title = cItem.title
        }
      }
    })
    return title
  }
  logout = () => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '确定退出吗?',
      onOk: () => {
        // 删除保存的user数据
        storageUtils.removeUser()
        memory.user = {}
        // 跳转到login页面
        this.props.history.replace('/login')
      }
    });
  }
  // 第一次render之后执行一次 一般在此执行异步操作：发送ajax请求、启动定时器
  componentDidMount() {
    this.getTime()
    this.getWeather()
  }
  // 当前组件卸载之前
  componentWillUnmount() {
    // 清除定时器
    clearInterval(this.intervalID)
  }
  render() {
    const {currentTime, dayPictureUrl, weather} = this.state
    const username = memory.user.username
    const title = this.getTitle()
    return (
      <div className="header">
        <div className="header_top">
          <span>欢迎，{username}</span>
          <Button type="link" onClick={this.logout}>退出</Button>
        </div>
        <div className="header_bottom">
          <div className="hander_bottom_left">
            <span>{title}</span>
          </div>
          <div className="hander_bottom_rigth">
            <span>{currentTime}</span>
            <img src={dayPictureUrl} alt="weather" />
            <span>{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}
export default withRouter(Header)